package com.lzk.controller.front;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
import com.lzk.model.ZcData;
import com.lzk.model.ZcUser;
import com.lzk.service.UserService;
import com.lzk.service.impl.UserServiceImpl;
import com.lzk.util.Util;
import com.lzk.util.VerifyCode;
import com.lzk.validator.FrontUserValidator;
import com.lzk.validator.UserValidator;

@Path("/front/user")
public class UserController extends FrontBaseController{
	public static Map<String,ZcUser> tokenMap = new HashMap<String, ZcUser>();
	
	UserService us = new UserServiceImpl();

	public void getVerifyCode() {
		VerifyCode verifyCode = new VerifyCode();
		getSession().setAttribute("code", verifyCode.getCode());
		renderJson(Ret.ok("data",verifyCode.getImg()));
	}
	
	@Before(FrontUserValidator.class)//为空验证
	public void login() {//登录验证
		String userName = getPara("userName");
		String pwd = getPara("pwd");
		String verifyCode = getPara("verifyCode");
		if (getSession().getAttribute("code")==null) {
			renderJson(Ret.fail("验证码已失效，请重试！"));
		}else {
			String sessionCode = (String)getSession().getAttribute("code");
			if (verifyCode.toUpperCase().equals(sessionCode.toUpperCase())) {
				//下一步验证
				boolean flag = us.login(userName, pwd, getResponse());
				if (flag) {
					renderJson(Ret.ok("登陆成功！"));
				}else {
					renderJson(Ret.fail("登录失败，账户密码错误或状态非正常！"));
				}
			}else {
				renderJson(Ret.fail("验证码错误，请重试！"));
			}
		}
	}
	
	public void checkUserName() {
		String userName = getPara("userName");
		boolean flag = us.checkUserName(userName);
		if(flag) {
			renderJson(Ret.fail("用户名重复！"));
		}else {
			renderJson(Ret.ok("用户名不重复！"));
		}
	}
	
	@Before(UserValidator.class)
	public void register() {
		//二进制流文件上传
		UploadFile uf = getFile();
		//文件移动
		//默认在哪里？
		String fileName = Util.moveFileToDireTory(uf.getFile(), PropKit.get("userHeadImg"));
		ZcUser user = getBean(ZcUser.class,"");
		ZcData rightStatus = ZcData.dao.findFirst("SELECT * FROM `zc_data` WHERE `key` = ? AND `value` = ?","userStatus","正常");
		user.setUserStatus(rightStatus.getValueId());
		if(fileName==null) {
			renderJson(Ret.fail("文件上传失败！"));
		}else {
			user.setHeadImg(fileName);
		}
		boolean flag = us.insertUser(user);
		if (flag) {
			renderJson(Ret.ok("添加成功！"));
		}else {
			renderJson(Ret.fail("添加失败！"));
		}
		
	}
}
